package com.hyphenate.easeui.widget;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.model.EaseImageCache;
import com.hyphenate.util.ImageUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoView;


public class ShowImagesDialog2 extends Dialog {

    private View mView;
    private Context mContext;
    private ViewPager mViewPager;
    private TextView mIndexText;
    private List<String> mImgUrls;
    private List<String> mTitles;
    private List<View> mViews;
    private List<String> msgIds;

    private FrameLayout mClose;
    private FrameLayout mShareOrSave;
    private FrameLayout fl_conversation;
    private RelativeLayout mRlPhotoTop;
    private RelativeLayout mRlPhotoBottom;
    private LinearLayout ll_save_or_share;
    private TextView tv_share;
    private TextView tv_save;
    private TextView tv_cancel;
    private TextView tv_like_count;
    private TextView tv_write_count;
    private TextView tv_content;

    private LinearLayout ll_like;
    private LinearLayout ll_write;

    private ImageView iv_like;

    private boolean isLike;


    private int position;
    private String content;
    private String path;
    private ProgressDialog pd;
    private Bitmap bitmap;
    private PhotoView photoView;
    private int default_res = R.drawable.ease_default_image;
    private ShowImagesAdapter mAdapter;

    public ShowImagesDialog2(@NonNull Context context,String content, List<String> imgUrls,List<String> msgIds, int position) {
        super(context, R.style.AppTheme);
        this.mContext = context;
        this.mImgUrls = imgUrls;
        this.msgIds = msgIds;
        this.position = position;
        initView();
        initData();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initView() {
        mView = View.inflate(mContext, R.layout.dialog_images_brower, null);

        mViewPager = mView.findViewById(R.id.vp_images);
        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        break;

                }
                return false;
            }
        });

        mClose = mView.findViewById(R.id.fl_close);
        mIndexText = mView.findViewById(R.id.tv_image_index);
        mRlPhotoTop = mView.findViewById(R.id.rl_photo_top);

        mClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        mTitles = new ArrayList<>();
        mViews = new ArrayList<>();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(mView);
        Window window = getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = 0;
        wl.gravity = Gravity.CENTER;
        window.setAttributes(wl);
        mViewPager.setCurrentItem(position);
        mIndexText.setText(position + 1 + "/" + mImgUrls.size());
    }

    private void initData() {
        for (int i = 0; i < mImgUrls.size(); i++) {
            photoView = new PhotoView(mContext);
            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            photoView.setLayoutParams(layoutParams);
          //  photoView.setOnPhotoTapListener(listener);
            //显示超长图
            RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE).skipMemoryCache(true);
           // photoView.setImage(ImageSource.uri(mImgUrls.get(i)));
            path = mImgUrls.get(i);
            if (new File(path).exists()) {
                Glide.with(mContext).load(path).into(photoView);
            }else {
                if(msgIds != null && msgIds.size() > 0){
                    downloadImage(msgIds.get(i));
                }
            }
            mViews.add(photoView);
            mTitles.add(i + "");
        }

        mAdapter = new ShowImagesAdapter(mViews, mTitles);
        mViewPager.setAdapter(mAdapter);
        mIndexText.setText(1 + "/" + mImgUrls.size());
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mIndexText.setText(position + 1 + "/" + mImgUrls.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void downloadImage(String msgId) {
        String str1 = mContext.getResources().getString(R.string.Download_the_pictures);
        pd = new ProgressDialog(mContext);
        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
     //   pd.setCanceledOnTouchOutside(false);
        pd.setMessage(str1);
      //  pd.show();
        File temp = new File(path);
        final String tempPath = temp.getParent() + "/temp_" + temp.getName();
        final EMCallBack callback = new EMCallBack() {
            @Override
            public void onSuccess() {
               // initData();
                Looper.prepare();
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        new File(tempPath).renameTo(new File(path));

                        DisplayMetrics metrics = new DisplayMetrics();
                        getOwnerActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
                        int screenWidth = metrics.widthPixels;
                        int screenHeight = metrics.heightPixels;

                        bitmap = ImageUtils.decodeScaleImage(path, screenWidth, screenHeight);
                        if (bitmap == null) {
                            photoView.setImageResource(default_res);
                        } else {
                            photoView.setImageBitmap(bitmap);
                            EaseImageCache.getInstance().put(path, bitmap);
                        }
                      //  mViews.add(photoView);
                        if (pd != null) {
                            pd.dismiss();
                        }
                    }
                });
                Looper.loop();


               /* if (null != getOwnerActivity())
                getOwnerActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });*/
            }

            @Override
            public void onError(int error, String msg) {
                File file = new File(tempPath);
                if (file.exists()&&file.isFile()) {
                    file.delete();
                }
                if (null != getOwnerActivity())
                getOwnerActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                            if (null != getOwnerActivity())
                            if ( getOwnerActivity().isFinishing() ||  getOwnerActivity().isDestroyed()) {
                                return;
                            }
                        }
                        photoView.setImageResource(default_res);
                        pd.dismiss();
                    }
                });
            }

            @Override
            public void onProgress(final int progress, String status) {
                final String str2 = mContext.getResources().getString(R.string.Download_the_pictures_new);
                pd.setMessage(str2 + progress + "%");
                Looper.prepare();
                 new Handler().post(new Runnable() {
                     @Override
                     public void run() {
                         pd.setMessage(str2 + progress + "%");
                     }
                 });
                Looper.loop();



                /*if (null != getOwnerActivity())
                getOwnerActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });*/
            }
        };

        EMMessage msg = EMClient.getInstance().chatManager().getMessage(msgId);
        msg.setMessageStatusCallback(callback);

        EMClient.getInstance().chatManager().downloadAttachment(msg);
    }




    public boolean isLike() {
        return isLike;
    }

}
